package com.ff.device.service.impl;

import com.ff.device.dao.DeviceInfoRepository;
import com.ff.device.domain.DeviceInfo;
import com.ff.device.result.CodeMsg;
import com.ff.device.result.Result;
import com.ff.device.service.DeviceService;
import com.ff.device.util.DeviceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    DeviceInfoRepository deviceInfoRepository;

    /**
     * 从本地数据库中获取设备
     * @return
     */
    @Override
    public List<DeviceInfo> getDeviceList() {
        return deviceInfoRepository.findAll();
    }

    @Override
    public boolean addDevice(String ip) {
        boolean result= DeviceUtil.connectedToDevice(ip);
        if (result){
            result=changeDeviceInfo(ip,1);
        }
        return result;
    }

    @Override
    public boolean delDevice(String ip) {
        boolean result= DeviceUtil.disConnectedToDevice(ip);
        if (result){
            result=changeDeviceInfo(ip,0);
        }
        if (result)
            return result;
        result=!checkDeviceExist(ip);
        return result;
    }

    private boolean changeDeviceInfo(String ip,int status){
        try {
            String devid=DeviceUtil.getDevid(ip);
            DeviceInfo deviceInfo=deviceInfoRepository.findDeviceInfoByDevid(devid);
            deviceInfo.setStatus(status);
            deviceInfo.setDeviceIp(ip);
            deviceInfoRepository.save(deviceInfo);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void updateDevice(List<DeviceInfo> localDeviceList) {
        deviceInfoRepository.saveAll(localDeviceList);
    }

    @Override
    public boolean updateDevice(DeviceInfo deviceInfo) {
        DeviceInfo savedDeviceInfo=deviceInfoRepository.save(deviceInfo);
        return true;
    }

    @Override
    public DeviceInfo findByDeviceInfo(String devid) {
        return deviceInfoRepository.findDeviceInfoByDevid(devid);
    }

    @Override
    public boolean checkDeviceExist(String deviceIp){
        boolean deviceExists=false;
        for (DeviceInfo deviceInfo:getDeviceList()){
            if (deviceInfo.getDeviceIp().contains(deviceIp)){
                deviceExists=true;
                break;
            }
        }
        return deviceExists;
    }
}
